package liyujie.dao;

import liyujie.model.Goodstype;
import liyujie.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TypeDao {
    public boolean add(String name, String remark){
        int result = 0;
        try {
            Connection conn = DBUtil.getConnection();
            String insert_sql = "insert into sm_goodstype values(null,?,?)";
            PreparedStatement pstmt = conn.prepareStatement(insert_sql);
            pstmt.setString(1, name);
            pstmt.setString(2, remark);
            result = pstmt.executeUpdate();
            DBUtil.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result==1;
    }
    public List<Goodstype> getAllGoodsType() {
        List<Goodstype> list = new ArrayList<>();
        try {
            Connection conn = DBUtil.getConnection();
            String sql = "select * from sm_goodstype";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String remark = rs.getString("remark");
                list.add(new Goodstype(id, name, remark));

            }
            DBUtil.closeConnection(conn);
        }  catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;
    }
}
